<template>
  <div class="search">
    <div class="search-wrapper">
      <div class="search-content">
        <el-input
          placeholder="请输入菜名"
          v-model="searchName">
          <i slot="prefix" class="el-input__icon el-icon-search" style="color:#f76763;font-weight:700;"></i>
          <i slot="suffix" class="el-input__icon el-icon-close" @click="deleteSearchName"></i>
        </el-input>
      </div>
      <div class="goods-wrapper" v-loading="loading1">
        <ul>
          <li class="foods-item" v-for="(food,index) in allGoods" :key="index">
            <div class="food-item" v-for="(food1,index1) in searchFoods" :key="index1" v-if="food.id===food1.id"
            >
              <div class="icon">
                <!--<img width="80" height="80" :src="food.icon" alt="">-->
                <img width="80" height="80" style="float:left;"
                     :src="food.foodspic"
                     alt="">
                <div class="sell_out" v-if="food.static_sold_out==='售罄'"></div>
              </div>
              <div class="food-content">
                <h2 class="name">{{food.foodsname}}</h2>
                <div class="spec">
              <span v-for="(item,index) in JSON.parse(food.specifications)" :key="index">
                  <span class="spec-one" v-for="(subitem,subkey,subindex) in item" :key="subindex"
                        v-if="subkey!=='price'">{{subkey}}</span>
              </span>
                </div>
                <div class="price">
                  <span v-for="(item,key,index) in JSON.parse(food.specifications)[0]" :key="index">¥{{item/100}}</span>
                  <span class="cartcontrol-wrapper" v-if="food.static_sold_out!=='售罄'">
                <CartControl :food="food" :all-goods="allGoods" @closespec="closeSpec" @refreshselectfoods="refreshSelectFoods"
                             @showshopcart="showShopCart"></CartControl>
              </span>
                </div>
              </div>
            </div>
          </li>
        </ul>
        <div class="empty" v-if="searchFoods.length===0">空</div>
      </div>
    </div>
    <div>
      <ShopCart :select-foods="selectFoods" :all-goods="allGoods" ref="shopcart" @refreshselectfoods="refreshSelectFoods"></ShopCart>
    </div>
    <div class="choose-spec" :class="{'specshow':specshow}">
      <div class="spec-header">
        <span class="name">{{chooseFood.foodsname}}</span>
        <span class="price">
          <span v-for="(item,key,index) in JSON.parse(chooseFood.specifications)" :key="index">
            <span class="spec-name" v-for="(item1,key1,index1) in item" :key="index1" v-if="key===0">
              ¥{{item1/100}}
            </span>
          </span>
        </span>
      </div>
      <div class="spec-content">
        <span class="desc">规格选择：</span>
        <span v-for="(item,key,index) in JSON.parse(chooseFood.specifications)" :key="index">
          <span @click="chooseSpec(key1,item1,key)" class="spec-name" v-for="(item1,key1,index1) in item" :key="index1"
                :class="{'spec-name-choose':key===specNameChoose}">
            {{key1}}(¥{{item1/100}})
          </span>
        </span>
      </div>
    </div>
    <div class="list-mask" @click="clickMask" v-show="mask"></div>
    <div class="cant-click" v-show="cantClick">餐桌状态已改变 <br> 请重新扫码入</div>
  </div>
</template>

<script>
  import Vue from 'vue';
  import axios from 'axios';
  import {basePath} from '../api/api_const';
  import ShopCart from './ShopCart'
  import CartControl from './CartControl'
  import Refresh from './Refresh'

  export default {
    inject: ['reload'],
    name: 'search',
    components: {
      ShopCart,
      CartControl,
      Refresh
    },
    data() {
      return {
        searchName: localStorage.getItem('searchName'),
        allGoods: [],
        searchFoods: [],
        loading: false,
        chooseFood: {
          specifications: '[{"小":"10"},{"中":"20"},{"大":"30"}]'
        }, // 选择的菜品规格
        specshow: false,
        specNameChoose: 0, // 默认第一个规格被高亮
        mask: false,
        cantClick: false, // 中间购物车没有该桌数据不能继续点餐
        websock: null
      }
    },
    computed: {
      selectFoods() {
        let foods = [];
        this.allGoods.forEach((good) => {
          if (good.count) {
            foods.push(good);
          }
        });
        return foods;
      }
    },
    watch: {
      // 监听输入框searchName值的变化
      searchName() {
        localStorage.setItem('searchName', this.searchName);
        if (localStorage.getItem('searchName') !== '') {
          this.searchFoods = [];
          JSON.parse(localStorage.getItem(localStorage.getItem('tableid') + '_localAllGoods')).forEach((food) => {
            if (food.foodsname.indexOf(this.searchName) !== -1) {
              this.searchFoods.push(food);
            }
          });
        } else {
          this.searchFoods = [];
        }
      }
    },
    methods: {
      // 删除搜索的菜名
      deleteSearchName() {
        this.searchName = '';
        localStorage.setItem('searchName', this.searchName);
      },
      // 初始化数据查询该门店下出所有goods
      getAllGoods() {
        this.loading1 = true;
        axios({
          method: 'get',
          url: basePath + 'xzg_order/query_foods_order?storeId=' + localStorage.getItem('storeid') + '&static_up_and_down=上市&s=order_sort'
        })
          .then((result) => {
            let res = JSON.parse(result.request.response);
            this.allGoods = res.response.data;
            this.allGoods.forEach((good) => {
              if (good.specifications[0] === '{') {
                good.specifications = '[' + good.specifications + ']';
              } else {
                // 对规格进行排序
                let spec = JSON.parse(good.specifications);
                let specPriceArr = []; // 所有价格放入数组
                spec.forEach((item, key, spec) => {
                  for (let key1 in item) {
                    specPriceArr.push(item[key1]);
                  }
                });
                // 将数组中价格排序
                for (let i = 0; i < specPriceArr.length; i++) {
                  for (let j = i + 1; j < specPriceArr.length; j++) {
                    if (specPriceArr[i] > specPriceArr[j]) {
                      let tmp = specPriceArr[i];
                      specPriceArr[i] = specPriceArr[j];
                      specPriceArr[j] = tmp;
                    }
                  }
                }
                let specArr = [];// 从小到大排序后的数组
                for (let ii = 0; ii < specPriceArr.length; ii++) {
                  spec.forEach((item, key, spec) => {
                    for (let key1 in item) {
                      if (item[key1] === specPriceArr[ii]) {
                        specArr.push(item)
                      }
                    }
                  });
                }
                good.specifications = JSON.stringify(specArr);
              }
            });
            // localStorage.setItem('localAllGoods', JSON.stringify([]));
            // 将之前点的菜赋值到新查的菜品上
            // if (localStorage.getItem(localStorage.getItem('tableid') + '_localAllGoods') !== null) {
            //   JSON.parse(localStorage.getItem(localStorage.getItem('tableid') + '_localAllGoods')).forEach((val) => {
            //     if (val.count) {
            //       this.allGoods.forEach((key2, i2, val2) => {
            //         if (val.id === key2.id) {
            //           Vue.set(this.allGoods[i2], 'count', val.count);
            //           Vue.set(this.allGoods[i2], 'chooseSpecs', val.chooseSpecs);
            //           Vue.set(this.allGoods[i2], 'nickname', val.nickname);
            //           Vue.set(this.allGoods[i2], 'headimgurl', val.headimgurl);
            //           Vue.set(this.allGoods[i2], 'openid', val.openid);
            //         }
            //       })
            //     }
            //   });
            // } else {
            //   localStorage.setItem(localStorage.getItem('tableid') + '_localAllGoods', JSON.stringify(this.allGoods));
            // }
            axios({
              method: 'get',
              url: basePath + 'xzg_order/add_order_info',
              params: {
                table_num: localStorage.getItem('tableid')
              }
            })
              .then((data) => {
                let res = JSON.parse(data.request.response);
                if (res.response.data.length > 0) {
                  JSON.parse(decodeURIComponent(res.response.data[0].order_info)).forEach((val) => {
                    if (val.count) {
                      this.allGoods.forEach((key2, i2, val2) => {
                        if (val.id === key2.id) {
                          Vue.set(this.allGoods[i2], 'count', val.count);
                          Vue.set(this.allGoods[i2], 'chooseSpecs', val.chooseSpecs);
                          Vue.set(this.allGoods[i2], 'nickname', val.nickname);
                          Vue.set(this.allGoods[i2], 'headimgurl', val.headimgurl);
                          Vue.set(this.allGoods[i2], 'openid', val.openid);
                        }
                      })
                    }
                  });
                }
              })
              .catch(function (err) {
                console.log(err);
              });
            localStorage.setItem(localStorage.getItem('tableid') + '_localAllGoods', JSON.stringify(this.allGoods));
            this.loading1 = false;
            console.log(this.allGoods);
            console.log('search页面--上面显示所有商品');
          })
          .catch(function (err) {
            console.log(err);
          });
      },
      initSearchFoods() {
        if (localStorage.getItem('searchName') !== null && localStorage.getItem('searchName') !== '') {
          this.searchName = localStorage.getItem('searchName');
          JSON.parse(localStorage.getItem(localStorage.getItem('tableid') + '_localAllGoods')).forEach((food) => {
            if (food.foodsname.indexOf(this.searchName) !== -1) {
              this.searchFoods.push(food);
            }
          });
        } else {
          this.searchFoods = [];
        }
      },
      // 接受子组件传来id展示规格
      closeSpec(food) {
        this.chooseFood = food;
        this.specNameChoose = 0;// 初始化高亮选中的规格

        this.specshow = true;
        this.mask = true;
      },
      // 隐藏面具-黑色背景
      clickMask() {
        this.mask = false;
        this.specshow = false;
      },
      // 显示购物车
      showShopCart(bool) {
        this.$refs.shopcart.showShopCart(false);
        // this.specshow = true;
        // this.mask = true;
      },
      // 选择规格
      chooseSpec(specName, specPrice, index) {
        this.specNameChoose = index;// 高亮选中的规格
        if (!this.chooseFood.count) {
          Vue.set(this.chooseFood, 'count', 1);
        } else {
          this.chooseFood.count++;
        }
        if (!this.chooseFood.chooseSpecs) {
          Vue.set(this.chooseFood, 'chooseSpecs', [[1, specName, specPrice, localStorage.getItem('nickname'), localStorage.getItem('headimgurl'), localStorage.getItem('openid')]]);
        } else {
          let isHave = 0;
          for (let i = 0; i < this.chooseFood.chooseSpecs.length; i++) {
            if (this.chooseFood.chooseSpecs[i][1] === specName) {
              isHave = 1;
              this.chooseFood.chooseSpecs[i][0]++;
            }
          }
          if (isHave === 0) {
            this.chooseFood.chooseSpecs.push([1, specName, specPrice, localStorage.getItem('nickname'), localStorage.getItem('headimgurl'), localStorage.getItem('openid')]);
          }
        }
        localStorage.setItem(localStorage.getItem('tableid') + '_localAllGoods', JSON.stringify(this.allGoods));
        this.refreshSelectFoods(); // 更新购物车
        this.specshow = false;
        this.mask = false;
      },
      // 向组发送数据
      refreshSelectFoods(e) {
        let data = encodeURIComponent(JSON.stringify(this.selectFoods));
        let togroup = '{"type":"togroup","group":"' + localStorage.getItem('tableid') + '","openid":"' + localStorage.getItem('openid') + '","data":"' + data + '"}';
        this.websocketsend(togroup);// 给组发送websocket请求
        // 保存点的菜品用来再次进入时更新菜品
        // 修改
        axios({
          method: 'post',
          url: basePath + 'xzg_order/update_order_info',
          data: {
            table_num: localStorage.getItem('tableid'),
            order_info: data,
            customer_num: localStorage.getItem('num-on-index')
          }
        })
          .then((data2) => {
            let res = JSON.parse(data2.request.response);
            console.log(res);
            if (res.response.data === 'false') {
              this.cantClick = true;
              // alert('餐桌状态已改变请重新扫码进入');
            } else {
              console.log('修改');
            }
          })
          .catch(function (err) {
            console.log(err);
          });
        // axios({
        //   method: 'get',
        //   url: basePath + 'xzg_order/add_order_info',
        //   params: {
        //     table_num: localStorage.getItem('tableid')
        //   }
        // })
        //   .then((data1) => {
        //     let res = JSON.parse(data1.request.response);
        //     if (res.response.data.length > 0) {
        //       // 修改
        //       axios({
        //         method: 'post',
        //         url: basePath + 'xzg_order/update_order_info',
        //         data: {
        //           table_num: localStorage.getItem('tableid'),
        //           order_info: data,
        //           customer_num: localStorage.getItem('num-on-index')
        //         }
        //       })
        //         .then((data2) => {
        //           let res = JSON.parse(data2.request.response);
        //           console.log(res);
        //           console.log('修改');
        //         })
        //         .catch(function (err) {
        //           console.log(err);
        //         });
        //     } else {
        //       // 新增
        //       axios({
        //         method: 'post',
        //         url: basePath + 'xzg_order/add_order_info',
        //         data: {
        //           table_num: localStorage.getItem('tableid'),
        //           order_info: data,
        //           customer_num: localStorage.getItem('num-on-index')
        //         }
        //       })
        //         .then((data2) => {
        //           let res = JSON.parse(data2.request.response);
        //           console.log(res);
        //           console.log('新增');
        //         })
        //         .catch(function (err) {
        //           console.log(err);
        //         });
        //     }
        //     console.log(res.response.data.length);
        //   })
        //   .catch(function (err) {
        //     console.log(err);
        //   });
      },
      // websocket
      initWebSocket() { // 初始化weosocket
        const wsuri = 'ws://101.37.202.109:8283';// ws地址
        // const wsuri = 'ws://127.0.0.1:8283';// ws地址
        this.websock = new WebSocket(wsuri);
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onclose = this.websocketclose;
      },
      // 数据接收
      websocketonmessage(e) {
        let message = JSON.parse('[' + e.data + ']')[0];
        console.log(message);
        switch (message.type) {
          case 'init':
            let join = '{"type":"join","group":"' + localStorage.getItem('tableid') + '","openid":"' + localStorage.getItem('openid') + '"}';
            this.websocketsend(join);// 发送websocket请求 加入socket组
            return;
          case 'togroup':
            let otherOrder = JSON.parse(decodeURIComponent(message.data));
            // 先清空购物车
            this.selectFoods.forEach((food) => {
              food.count = 0;
              food.chooseSpecs = undefined;
              food.nickname = null;
              food.headimgurl = null;
              food.openid = null;
            });
            otherOrder.forEach((good) => {
              this.allGoods.forEach((food, i, val) => {
                if (good.id === food.id) {
                  Vue.set(this.allGoods, i, good);
                }
              })
            });
            localStorage.setItem(localStorage.getItem('tableid') + '_localAllGoods', JSON.stringify(this.allGoods));
            return;
        }
        console.log('欢迎加入' + localStorage.getItem('tableid') + '组');
      },
      // 数据发送
      websocketsend(agentData) {
        this.websock.send(agentData);
      },
      websocketclose(e) { // 关闭
        console.log('connection closed (' + e.code + ')');
      }
    },
    created() {
      this.initWebSocket(); // 初始化websocket 加入组 类似群聊
      // this.searchName = localStorage.getItem('searchName');// 初始化搜索值
      this.getAllGoods();// 查询出门店下所有goods初始化
      this.initSearchFoods();
    }
  }
</script>

<style scoped lang="scss">
  .search {
    position: fixed;
    top: 0;
    left: 0;
    bottom: 48px;
    z-index: 10;
    width: 100%;
    background: #fff;
    .search-wrapper {
      .search-content {
        padding: 10px 16px 0;
      }
    }
    .goods-wrapper {
      position: absolute;
      top: 60px;
      bottom: 0;
      left: 0;
      width: 100%;
      overflow-y: auto;
      -webkit-overflow-scrolling: touch;
      /*overflow: auto;*/
      .foods-item {
        margin: 20px 16px;
        &:first-child {
          margin-top: -10px;
          padding-top: 10px;
        }
        &:last-child {
          border-bottom: 0;
          margin-bottom: 0;
        }
        .food-item {
          display: flex;
          padding-bottom: 9px;
          border-bottom: 1px dashed #dcdcdc;
          .icon {
            flex: 0 0 80px;
            margin-right: 10px;
            .sell_out{
              float:left;
              width:80px;
              height:80px;
              margin-top:-80px;
              background:#ccc;
              opacity:1;
              background: url('../assets/shouqing.png') no-repeat;
              -webkit-background-size: 50px;
              background-size: 50px;
              background-position: 15px 15px;
            }
          }
          .food-content {
            flex: 1;
            .name {
              margin: 2px 0 8px 0;
              min-height: 16px;
              line-height: 18px;
              font-size: 16px;
              color: #333;
            }
            .spec {
              min-height: 24px;
              .spec-one {
                display: inline-block;
                padding: 1px 5px;
                margin: 3px 5px 0 0;
                border-radius: 2px;
                border: 1px solid #ccc;
              }
            }
            .price {
              margin-top: 8px;
              color: #f76763;
              font-size: 16px;
              span {
                display: inline-block;
              }
              .cartcontrol-wrapper {
                display: inline-block;
                float: right;
              }
            }
          }
        }
      }
      .empty {
        position: relative;
        height: 300px;
        width: 100%;
        z-index: 2;
        line-height: 300px;
        text-align: center;
        font-size: 30px;
        color: rgba(247, 103, 99, 0.4);
      }
    }
    .choose-spec {
      position: fixed;
      bottom: -200px;
      left: 0;
      z-index: 3;
      width: 100%;
      /*padding-bottom: 10px;*/
      background-color: #fff;
      transition: bottom 0.7s;
      -moz-transition: bottom 0.7s;
      -webkit-transition: bottom 0.7s;
      &.specshow {
        bottom: 48px !important;
      }
      .spec-header {
        height: 60px;
        line-height: 60px;
        background: #f2f2f2;
        padding: 0 16px;
        .name {
          display: inline-block;
          font-size: 18px;
          color: #333;
        }
        .price {
          display: inline-block;
          float: right;
          font-size: 18px;
          color: #f76763;
        }
      }
      .spec-content {
        /*height: 100px;*/
        /*line-height: 100px;*/
        min-height: 50px;
        line-height: 50px;
        text-align: center;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
        /*overflow: auto;*/
        .desc {
          font-size: 16px;
          color: #333;
        }
        .spec-name {
          display: inline-block;
          margin: 0 3px;
          padding: 0 5px;
          min-width: 50px;
          height: 40px;
          line-height: 40px;
          border-radius: 4px;
          border: 1px solid #ccc;
          color: #333;
          font-size: 16px;
          &.spec-name-choose {
            background: #f76763;
            color: #fff;
            border: 1px solid #f76763;
          }
        }
      }
    }
    .list-mask {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 2;
      /*opacity: 0.9;*/
      background: rgba(76, 76, 76, 0.9);
    }
    .cant-click {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      padding-top: 200px;
      font-size: 30px;
      text-align: center;
      color: #ccc;
      z-index: 2000;
      background: rgba(76, 76, 76, 0.9);
    }
  }
</style>
